package cn.qingyun.gis.modules.init.utils;

import cn.qingyun.gis.modules.init.system.constant.SystemConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
public class HttpRequestUtil {
    /**
     * 连接时间
     */
    private static int connectTimeout = 30000;

    /**
     * 响应时间
     */
    private static int readTimeout = 60000;

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static Map<String, String> sendGet(String url, String param) {
        return sendGet(url, param, "application/x-www-form-urlencoded");
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url         发送请求的URL
     * @param param       请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 媒体类型
     * @return URL 所代表远程资源的响应结果
     */
    public static Map<String, String> sendGet(String url, String param, String contentType) {
        return sendGet(url, param, contentType, connectTimeout, readTimeout);
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url            发送请求的URL
     * @param param          请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType    媒体类型
     * @param connectTimeout 连接时间
     * @param readTimeout    响应时间
     * @return URL 所代表远程资源的响应结果
     */
    public static Map<String, String> sendGet(String url, String param, String contentType, int connectTimeout, int readTimeout) {
        String result = "";
        BufferedReader in = null;
        Map<String, String> resultMap = new HashMap<>();
        try {
            if (!StringUtils.isEmpty(param)) {
                if (url.indexOf("?") > 0) {
                    url = url + "&" + param;
                } else {
                    url = url + "?" + param;
                }
            }
            Map<String, String> headerMap = new HashMap<>(2);
            headerMap.put("Content-Type", contentType);
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = HttpSetProxyUtil.openNetConnection(realUrl, headerMap, connectTimeout, readTimeout);
            // 建立实际的连接
            conn.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = conn.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), SystemConstant.UTF8));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            resultMap.put("result", result);
            List<String> totalList = map.get("X-Total");
            if (totalList != null && totalList.size() > 0) {
                resultMap.put("total", map.get("X-Total").get(0));
            }
        } catch (Exception e) {
            resultMap.put("result", "ERROR");
            throw unchecked("sendGet method error: " + e);
        } finally {
            // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                log.error("gitlab grant auth error:", e);
            }
        }
        return resultMap;
    }

    /***
     *
     * @Description 向指定URL发送POST方法的请求，不走代理
     * @Param [stringBuilder, params]
     * @return java.lang.String
     **/
    public static String sendPostNoneProxy(HttpEntity params, HttpPost httpPost) throws IOException {
        httpPost.setEntity(params);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            return result;
        }
        return null;
    }

    /***
     *
     * @Description 向指定URL发送POST方法的请求，走代理
     * @Author: wuBin
     * @Date 15:35 2021/6/30
     * @Param [stringBuilder, params]
     * @return java.lang.String
     **/
    public static String postSet(HttpEntity params, HttpPost httpPost) throws IOException {
        httpPost.setEntity(params);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpHost proxy = needNetProxy();
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            return EntityUtils.toString(entity, "UTF-8");
        }
        return null;
    }

    //获取proxy
    public static HttpHost needNetProxy() {
        //添加proxy校验
        //查询当前是否有proxy
        //String proxySet = System.getProperty("java.net.useSystemProxies");//全局配置，默认不需要了--会影响别的接口调用
        String proxyHost = System.getProperty("http.vpHost");
        String proxyPort = System.getProperty("http.vpPort");

        if (null != proxyHost && !"".equals(proxyHost)
                && null != proxyPort && !"".equals(proxyPort)) {

            Integer port = Integer.parseInt(proxyPort);
            log.debug("port is :{}", port);
            return new HttpHost(proxyHost, port);
        } else {
            log.error("http.vpHost 或者 http.vpHost vm 参数设置错误");
            return null;
        }
    }

    /**
     * 将error info转换为UncheckedException.
     */
    public static RuntimeException unchecked(String errorInfo) {
        if (null != errorInfo) {
            return new RuntimeException(errorInfo);
        } else {
            return new RuntimeException();
        }
    }

    //发送delete请求
    public static void doDelete(String url) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpHost proxy = needNetProxy();
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpDelete.setConfig(requestConfig);
        httpDelete.setHeader("Content-type", "application/json");
        httpDelete.setHeader("DataEncoding", "UTF-8");
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpDelete);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

